<!DOCTYPE html>
<html>
<head lang="en">
	<base href="/">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta charset="UTF-8">
	<title>我的</title>
	<link href="css/base.css" type="text/css" rel="stylesheet">
	<link href="css/address.css" type="text/css" rel="stylesheet">
	<!--[if lt IE 9]>
	<script src="js/html5shiv.js"></script>
	<script src="js/respond.js"></script>
	<![endif]-->
</head>
<body>
<div class="my">
	<header>
		<a class="fl" href="#"><i class="iconfont">&#xe624;</i></a>
		<h2>管理收货地址</h2>
		<a href="#"><i class="iconfont">&#xe62b;</i></a>
	</header>
	<div class="address" id="addressList">
		<!-- 地址列表将通过 JavaScript 动态生成 -->
	</div>
</div>

<!--编辑弹框-->
<!--遮罩-->
<div class="mask"></div>
<div class="readd">
	<form id="editAddressForm" method="post">
		<label for="editContactName">联系人姓名：</label>
		<input type="text" id="editContactName" class="on" placeholder="请输入联系人姓名" />
		<br><br>

		<label for="editTel">手机号码：</label>
		<input type="text" id="editTel" placeholder="请输入手机号码" />
		<br><br>

		<label for="editProvince">省份：</label>
		<select id="editProvince">
			<option value="">请选择省份</option>
		</select>
		<input type="hidden" id="editProvincecode" name="provincecode">
		<br><br>

		<label for="editCity">城市：</label>
		<select id="editCity">
			<option value="">请选择城市</option>
		</select>
		<input type="hidden" id="editCitycode" name="citycode">
		<br><br>

		<label for="editArea">区域：</label>
		<select id="editArea">
			<option value="">请选择区域</option>
		</select>
		<input type="hidden" id="editAreacode" name="areacode">
		<br><br>

		<label for="editDetailAddress">详细地址：</label>
		<textarea id="editDetailAddress" placeholder="请输入详细地址"></textarea>
		<br><br>

		<div class="bc">
			<input type="button" id="saveEdit" value="保存" />
			<input type="button" id="cancelEdit" value="取消" />
		</div>
	</form>
</div>
<!--删除的弹框-->
<div class="delmask">
	<div class="deltk">
		<p>确认删除地址？</p>
		<p>删除之后将无法恢复</p>
		<p>
			<a class="dqx" href="#" id="cancelDelete">取消</a>
			<a class="dqr" href="#" id="confirmDelete">确认</a>
		</p>
	</div>
</div>

<div style="padding-top: 4rem;"></div>
<!--------------------------footer----------------------->
<footer>
	<a href="index.html" class="on"><i class="iconfont">&#xe60d;</i><br /><span>首页</span></a>
	<a href="#"><i class="iconfont">&#xe6f4;</i><br /><span>分类</span></a>
	<a href="#"><i class="iconfont">&#xe601;</i><br /><span>搭配</span></a>
	<a href="#"><i class="iconfont">&#xe6cc;</i><br /><span>购物车</span></a>
	<a href="#"><i class="iconfont">&#xe607;</i><br /><span>我</span></a>
</footer>

<script src="js/jquery-1.12.4.min.js"></script>
<script src="js/public.js"></script>
<script src="js/rem.js" type="text/javascript" charset="utf-8"></script>
<script>
	$(document).ready(function() {
		// 高德地图 API 的密钥
		const amapKey = "d5e466c74f37e2b1f89163a68a161ea7";

		// 获取地址数据
		function loadAddresses() {
			$.ajax({
				url: "/address/getaddressbyuserid",
				type: "GET",
				success: function(response) {
					if (response && response.code === 0 && response.data) {
						renderAddresses(response.data);
					} else {
						$("#addressList").html("<p>暂无地址信息</p>");
					}
				},
				error: function(xhr, status, error) {
					console.error("获取地址数据失败:", error);
				}
			});
		}

		// 渲染地址列表
		function renderAddresses(addresses) {
			let html = "";
			addresses.forEach(address => {
				html += `
					<div class="addlist" data-addressid="${address.id}">
						<div class="top">
							<p>${address.name} ${address.tel}</p>
							<p>${address.province} ${address.city} ${address.area} ${address.address}</p>
						</div>
						<div class="bott clearfix">
							<div class="pro clearfix fl">
								<label class="fl">
									<input type="checkbox" ${address.isdefault === 1 ? "checked" : ""} />
									<span></span>
								</label>
								<span>设为默认</span>
							</div>
							<div class="fr">
								<a class="bj fl"><i class="iconfont">&#xe62b;</i>编辑</a>
								<a class="del fl"><i class="iconfont">&#xe62b;</i>删除</a>
							</div>
						</div>
					</div>
				`;
			});
			$("#addressList").html(html);
		}

		// 初始化加载地址数据
		loadAddresses();

		// 编辑地址
		$(document).on("click", ".bj", function() {
			const addressId = $(this).closest(".addlist").data("addressid");
			// 获取地址详细信息并填充到编辑表单
			$.ajax({
				url: `/address/getaddressbyid?id=${addressId}`,
				type: "GET",
				success: function(response) {
					if (response && response.code === 0 && response.data) {
						const address = response.data;
						$("#editContactName").val(address.name);
						$("#editTel").val(address.tel);
						$("#editDetailAddress").val(address.address);
						$("#editProvincecode").val(address.provincecode);
						$("#editCitycode").val(address.citycode);
						$("#editAreacode").val(address.areacode);

						// 加载省份、城市、区域数据
						loadProvinces(address.province, address.city, address.area);
						$(".mask, .readd").show(); // 显示编辑弹框
					}
				},
				error: function(xhr, status, error) {
					console.error("获取地址详情失败:", error);
				}
			});
		});

		// 保存编辑
		$("#saveEdit").click(function() {
			const addressId = $(".addlist").data("addressid");
			const data = {
				id: addressId,
				name: $("#editContactName").val(),
				tel: $("#editTel").val(),
				province: $("#editProvince").val(),
				city: $("#editCity").val(),
				area: $("#editArea").val(),
				provincecode: $("#editProvincecode").val(),
				citycode: $("#editCitycode").val(),
				areacode: $("#editAreacode").val(),
				address: $("#editDetailAddress").val()
			};

			$.ajax({
				url: "/address/update",
				type: "POST",
				data: data,
				success: function(response) {
					if (response && response.code === 0) {
						alert("地址更新成功！");
						loadAddresses(); // 重新加载地址列表
						$(".mask, .readd").hide(); // 隐藏编辑弹框
					} else {
						alert("地址更新失败，请重试！");
					}
				},
				error: function(xhr, status, error) {
					console.error("更新地址失败:", error);
					alert("更新地址失败，请重试！");
				}
			});
		});

		// 取消编辑
		$("#cancelEdit").click(function() {
			$(".mask, .readd").hide(); // 隐藏编辑弹框
		});

		// 删除地址
		$(document).on("click", ".del", function() {
			const addressId = $(this).closest(".addlist").data("addressid");
			$(".delmask").show(); // 显示删除确认弹框

			// 确认删除
			$("#confirmDelete").click(function() {
				$.ajax({
					url: `/address/delete?id=${addressId}`,
					type: "POST",
					success: function(response) {
						if (response && response.code === 0) {
							alert("地址删除成功！");
							loadAddresses(); // 重新加载地址列表
							$(".delmask").hide(); // 隐藏删除弹框
						} else {
							alert("地址删除失败，请重试！");
						}
					},
					error: function(xhr, status, error) {
						console.error("删除地址失败:", error);
						alert("删除地址失败，请重试！");
					}
				});
			});

			// 取消删除
			$("#cancelDelete").click(function() {
				$(".delmask").hide(); // 隐藏删除弹框
			});
		});

		// 加载省份数据
		function loadProvinces(selectedProvince = "", selectedCity = "", selectedArea = "") {
			const url = `https://restapi.amap.com/v3/config/district?key=${amapKey}&keywords=中国&subdistrict=1&extensions=base`;
			$.get(url, function(response) {
				if (response.status === "1" && response.districts.length > 0) {
					const provinces = response.districts[0].districts;
					$("#editProvince").empty().append('<option value="">请选择省份</option>');
					provinces.forEach(province => {
						$("#editProvince").append(`<option value="${province.name}" data-adcode="${province.adcode}">${province.name}</option>`);
					});

					// 设置选中的省份
					if (selectedProvince) {
						$("#editProvince").val(selectedProvince);
						$("#editProvince").trigger("change"); // 触发省份变化事件
					}

					// 设置选中的城市
					if (selectedCity) {
						setTimeout(() => {
							$("#editCity").val(selectedCity);
							$("#editCity").trigger("change"); // 触发城市变化事件
						}, 500);
					}

					// 设置选中的区域
					if (selectedArea) {
						setTimeout(() => {
							$("#editArea").val(selectedArea);
						}, 1000);
					}
				}
			});
		}

		// 当省份选择变化时，加载城市数据
		$("#editProvince").change(function() {
			const provinceName = $(this).val();
			const provinceCode = $(this).find(":selected").data("adcode");
			$("#editProvincecode").val(provinceCode); // 更新省份代码

			if (provinceName) {
				const url = `https://restapi.amap.com/v3/config/district?key=${amapKey}&keywords=${provinceName}&subdistrict=1&extensions=base`;
				$.get(url, function(response) {
					if (response.status === "1" && response.districts.length > 0) {
						const cities = response.districts[0].districts;
						$("#editCity").empty().append('<option value="">请选择城市</option>');
						cities.forEach(city => {
							$("#editCity").append(`<option value="${city.name}" data-adcode="${city.adcode}">${city.name}</option>`);
						});
					}
				});
			}
		});

		// 当城市选择变化时，加载区域数据
		$("#editCity").change(function() {
			const cityName = $(this).val();
			const cityCode = $(this).find(":selected").data("adcode");
			$("#editCitycode").val(cityCode); // 更新城市代码

			if (cityName) {
				const url = `https://restapi.amap.com/v3/config/district?key=${amapKey}&keywords=${cityName}&subdistrict=1&extensions=base`;
				$.get(url, function(response) {
					if (response.status === "1" && response.districts.length > 0) {
						const areas = response.districts[0].districts;
						$("#editArea").empty().append('<option value="">请选择区域</option>');
						areas.forEach(area => {
							$("#editArea").append(`<option value="${area.name}" data-adcode="${area.adcode}">${area.name}</option>`);
						});
					}
				});
			}
		});

		// 当区域选择变化时，更新区域代码
		$("#editArea").change(function() {
			const areaCode = $(this).find(":selected").data("adcode");
			$("#editAreacode").val(areaCode); // 更新区域代码
		});
	});
</script>
</body>
</html>